package com.example.myapp

import android.app.NotificationManager
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothSocket
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.provider.Settings
import androidx.annotation.NonNull
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.util.*

class MainActivity : FlutterActivity() {
    private val CHANNEL = "com.example.myapp/do_not_disturb"
    private val BLUETOOTH_CHANNEL = "com.example.myapp/bluetooth"
    private val notificationManager by lazy { 
        getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager 
    }
    private val bluetoothAdapter by lazy { BluetoothAdapter.getDefaultAdapter() }
    private var bluetoothSocket: BluetoothSocket? = null
    private var inputStream: InputStream? = null
    private var outputStream: OutputStream? = null
    
    // 设备发现相关
    private var discoveredDevices = mutableListOf<BluetoothDevice>()
    private var bluetoothChannel: MethodChannel? = null
    private var isReceiverRegistered = false
    
    // 蓝牙权限请求码
    private val BLUETOOTH_PERMISSION_REQUEST_CODE = 1001
    private val LOCATION_PERMISSION_REQUEST_CODE = 1002
    
    // 蓝牙设备发现广播接收器
    private val bluetoothReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            android.util.Log.d("BluetoothReceiver", "收到广播: ${intent.action}")
            when (intent.action) {
                BluetoothDevice.ACTION_FOUND -> {
                    val device: BluetoothDevice? = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)
                    android.util.Log.d("BluetoothReceiver", "发现设备: ${device?.name} - ${device?.address}")
                    device?.let {
                        if (!discoveredDevices.contains(it)) {
                            discoveredDevices.add(it)
                            android.util.Log.d("BluetoothReceiver", "添加设备到列表，当前设备数: ${discoveredDevices.size}")
                            // 通知Flutter端发现新设备
                            bluetoothChannel?.invokeMethod("onDeviceFound", mapOf(
                                "name" to (it.name ?: "未知设备"),
                                "address" to it.address,
                                "type" to it.type.toString()
                            ))
                        }
                    }
                }
                BluetoothAdapter.ACTION_DISCOVERY_STARTED -> {
                    android.util.Log.d("BluetoothReceiver", "扫描开始")
                    bluetoothChannel?.invokeMethod("onDiscoveryStarted", null)
                }
                BluetoothAdapter.ACTION_DISCOVERY_FINISHED -> {
                    android.util.Log.d("BluetoothReceiver", "扫描完成，发现设备数: ${discoveredDevices.size}")
                    bluetoothChannel?.invokeMethod("onDiscoveryFinished", null)
                }
            }
        }
    }

    override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        
        // 免打扰功能
        MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler { call, result ->
            when (call.method) {
                "enableDoNotDisturb" -> {
                    enableDoNotDisturb(result)
                }
                "disableDoNotDisturb" -> {
                    disableDoNotDisturb(result)
                }
                "isDoNotDisturbEnabled" -> {
                    isDoNotDisturbEnabled(result)
                }
                "checkNotificationPolicyPermission" -> {
                    checkNotificationPolicyPermission(result)
                }
                "openNotificationPolicySettings" -> {
                    openNotificationPolicySettings(result)
                }
                else -> {
                    result.notImplemented()
                }
            }
        }
        
        // 蓝牙功能
        bluetoothChannel = MethodChannel(flutterEngine.dartExecutor.binaryMessenger, BLUETOOTH_CHANNEL)
        bluetoothChannel?.setMethodCallHandler { call, result ->
            when (call.method) {
                "isBluetoothAvailable" -> {
                    isBluetoothAvailable(result)
                }
                "isBluetoothEnabled" -> {
                    isBluetoothEnabled(result)
                }
                "enableBluetooth" -> {
                    enableBluetooth(result)
                }
                "checkBluetoothPermissions" -> {
                    checkBluetoothPermissions(result)
                }
                "requestBluetoothPermissions" -> {
                    requestBluetoothPermissions(result)
                }
                "getPairedDevices" -> {
                    getPairedDevices(result)
                }
                "startScan" -> {
                    startScan(result)
                }
                "getDiscoveredDevices" -> {
                    getDiscoveredDevices(result)
                }
                "pairDevice" -> {
                    val address = call.argument<String>("address")
                    pairDevice(address, result)
                }
                "stopScan" -> {
                    stopScan(result)
                }
                "connectDevice" -> {
                    val address = call.argument<String>("address")
                    connectDevice(address, result)
                }
                "disconnect" -> {
                    disconnect(result)
                }
                "sendData" -> {
                    val data = call.argument<String>("data")
                    sendData(data, result)
                }
                "readData" -> {
                    readData(result)
                }
                "getConnectionState" -> {
                    getConnectionState(result)
                }
                else -> {
                    result.notImplemented()
                }
            }
        }
    }

    private fun enableDoNotDisturb(result: MethodChannel.Result) {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (notificationManager.isNotificationPolicyAccessGranted) {
                    notificationManager.setInterruptionFilter(NotificationManager.INTERRUPTION_FILTER_NONE)
                    result.success(true)
                } else {
                    result.error("PERMISSION_DENIED", "需要通知策略访问权限", null)
                }
            } else {
                result.error("UNSUPPORTED", "此功能需要Android 6.0及以上版本", null)
            }
        } catch (e: Exception) {
            result.error("ERROR", "启用免打扰失败: ${e.message}", null)
        }
    }

    private fun disableDoNotDisturb(result: MethodChannel.Result) {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (notificationManager.isNotificationPolicyAccessGranted) {
                    notificationManager.setInterruptionFilter(NotificationManager.INTERRUPTION_FILTER_ALL)
                    result.success(true)
                } else {
                    result.error("PERMISSION_DENIED", "需要通知策略访问权限", null)
                }
            } else {
                result.error("UNSUPPORTED", "此功能需要Android 6.0及以上版本", null)
            }
        } catch (e: Exception) {
            result.error("ERROR", "关闭免打扰失败: ${e.message}", null)
        }
    }

    private fun isDoNotDisturbEnabled(result: MethodChannel.Result) {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                val isEnabled = notificationManager.currentInterruptionFilter == NotificationManager.INTERRUPTION_FILTER_NONE
                result.success(isEnabled)
            } else {
                result.error("UNSUPPORTED", "此功能需要Android 6.0及以上版本", null)
            }
        } catch (e: Exception) {
            result.error("ERROR", "检查免打扰状态失败: ${e.message}", null)
        }
    }

    private fun checkNotificationPolicyPermission(result: MethodChannel.Result) {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                val hasPermission = notificationManager.isNotificationPolicyAccessGranted
                result.success(hasPermission)
            } else {
                result.error("UNSUPPORTED", "此功能需要Android 6.0及以上版本", null)
            }
        } catch (e: Exception) {
            result.error("ERROR", "检查权限状态失败: ${e.message}", null)
        }
    }

    private fun openNotificationPolicySettings(result: MethodChannel.Result) {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                val intent = Intent(Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS)
                startActivity(intent)
                result.success(true)
            } else {
                result.error("UNSUPPORTED", "此功能需要Android 6.0及以上版本", null)
            }
        } catch (e: Exception) {
            result.error("ERROR", "打开设置页面失败: ${e.message}", null)
        }
    }

    // 蓝牙相关方法
    private fun isBluetoothAvailable(result: MethodChannel.Result) {
        try {
            val available = bluetoothAdapter != null
            result.success(available)
        } catch (e: Exception) {
            result.error("ERROR", "检查蓝牙可用性失败: ${e.message}", null)
        }
    }

    private fun isBluetoothEnabled(result: MethodChannel.Result) {
        try {
            if (bluetoothAdapter == null) {
                result.error("UNAVAILABLE", "蓝牙不可用", null)
                return
            }
            val enabled = bluetoothAdapter.isEnabled
            result.success(enabled)
        } catch (e: Exception) {
            result.error("ERROR", "检查蓝牙状态失败: ${e.message}", null)
        }
    }

    private fun enableBluetooth(result: MethodChannel.Result) {
        try {
            if (bluetoothAdapter == null) {
                result.error("UNAVAILABLE", "蓝牙不可用", null)
                return
            }
            if (!bluetoothAdapter.isEnabled) {
                val intent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
                startActivityForResult(intent, BLUETOOTH_PERMISSION_REQUEST_CODE)
                result.success(true)
            } else {
                result.success(true)
            }
        } catch (e: Exception) {
            result.error("ERROR", "启用蓝牙失败: ${e.message}", null)
        }
    }

    private fun checkBluetoothPermissions(result: MethodChannel.Result) {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                val hasBluetoothConnect = ContextCompat.checkSelfPermission(this, android.Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED
                val hasBluetoothScan = ContextCompat.checkSelfPermission(this, android.Manifest.permission.BLUETOOTH_SCAN) == PackageManager.PERMISSION_GRANTED
                val hasLocation = ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                result.success(hasBluetoothConnect && hasBluetoothScan && hasLocation)
            } else {
                val hasBluetooth = ContextCompat.checkSelfPermission(this, android.Manifest.permission.BLUETOOTH) == PackageManager.PERMISSION_GRANTED
                val hasLocation = ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                result.success(hasBluetooth && hasLocation)
            }
        } catch (e: Exception) {
            result.error("ERROR", "检查蓝牙权限失败: ${e.message}", null)
        }
    }

    private fun requestBluetoothPermissions(result: MethodChannel.Result) {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                val permissions = arrayOf(
                    android.Manifest.permission.BLUETOOTH_CONNECT,
                    android.Manifest.permission.BLUETOOTH_SCAN,
                    android.Manifest.permission.ACCESS_FINE_LOCATION
                )
                ActivityCompat.requestPermissions(this, permissions, BLUETOOTH_PERMISSION_REQUEST_CODE)
            } else {
                val permissions = arrayOf(
                    android.Manifest.permission.BLUETOOTH,
                    android.Manifest.permission.ACCESS_FINE_LOCATION
                )
                ActivityCompat.requestPermissions(this, permissions, LOCATION_PERMISSION_REQUEST_CODE)
            }
            result.success(true)
        } catch (e: Exception) {
            result.error("ERROR", "请求蓝牙权限失败: ${e.message}", null)
        }
    }

    private fun getPairedDevices(result: MethodChannel.Result) {
        try {
            if (bluetoothAdapter == null) {
                result.error("UNAVAILABLE", "蓝牙不可用", null)
                return
            }
            
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                    result.error("PERMISSION_DENIED", "需要蓝牙连接权限", null)
                    return
                }
            }
            
            val pairedDevices = bluetoothAdapter.bondedDevices
            val deviceList = mutableListOf<Map<String, Any>>()
            
            for (device in pairedDevices) {
                deviceList.add(mapOf(
                    "name" to (device.name ?: "未知设备"),
                    "address" to device.address,
                    "type" to device.type.toString()
                ))
            }
            
            result.success(deviceList)
        } catch (e: Exception) {
            result.error("ERROR", "获取配对设备失败: ${e.message}", null)
        }
    }

    private fun startScan(result: MethodChannel.Result) {
        try {
            if (bluetoothAdapter == null) {
                result.error("UNAVAILABLE", "蓝牙不可用", null)
                return
            }
            
            // 检查蓝牙扫描权限
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED) {
                    android.util.Log.d("BluetoothScan", "缺少BLUETOOTH_SCAN权限")
                    result.error("PERMISSION_DENIED", "需要蓝牙扫描权限，请授予BLUETOOTH_SCAN权限", null)
                    return
                }
            }
            
            // 检查位置权限（Android 6.0+ 需要位置权限才能扫描蓝牙设备）
            if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                android.util.Log.d("BluetoothScan", "缺少位置权限")
                result.error("PERMISSION_DENIED", "需要位置权限才能扫描蓝牙设备", null)
                return
            }
            
            if (bluetoothAdapter.isDiscovering) {
                bluetoothAdapter.cancelDiscovery()
            }
            
            // 清空之前发现的设备
            discoveredDevices.clear()
            
            // 注册广播接收器
            if (!isReceiverRegistered) {
                val filter = IntentFilter().apply {
                    addAction(BluetoothDevice.ACTION_FOUND)
                    addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED)
                    addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)
                }
                registerReceiver(bluetoothReceiver, filter)
                isReceiverRegistered = true
            }
            
            val discoveryStarted = bluetoothAdapter.startDiscovery()
            android.util.Log.d("BluetoothScan", "开始扫描: $discoveryStarted")
            result.success(discoveryStarted)
        } catch (e: Exception) {
            result.error("ERROR", "开始扫描失败: ${e.message}", null)
        }
    }

    private fun stopScan(result: MethodChannel.Result) {
        try {
            if (bluetoothAdapter == null) {
                result.error("UNAVAILABLE", "蓝牙不可用", null)
                return
            }
            
            if (bluetoothAdapter.isDiscovering) {
                bluetoothAdapter.cancelDiscovery()
            }
            
            // 注销广播接收器
            if (isReceiverRegistered) {
                try {
                    unregisterReceiver(bluetoothReceiver)
                    isReceiverRegistered = false
                } catch (e: Exception) {
                    // 接收器可能未注册，忽略错误
                }
            }
            
            result.success(true)
        } catch (e: Exception) {
            result.error("ERROR", "停止扫描失败: ${e.message}", null)
        }
    }

    private fun getDiscoveredDevices(result: MethodChannel.Result) {
        try {
            val devices = discoveredDevices.map { device ->
                mapOf(
                    "name" to (device.name ?: "未知设备"),
                    "address" to device.address,
                    "type" to device.type.toString()
                )
            }
            result.success(devices)
        } catch (e: Exception) {
            result.error("ERROR", "获取发现的设备失败: ${e.message}", null)
        }
    }

    private fun pairDevice(address: String?, result: MethodChannel.Result) {
        try {
            if (address == null) {
                result.error("INVALID_ADDRESS", "设备地址无效", null)
                return
            }

            val device = bluetoothAdapter?.getRemoteDevice(address)
            if (device == null) {
                result.error("DEVICE_NOT_FOUND", "设备未找到", null)
                return
            }

            android.util.Log.d("BluetoothPair", "开始配对设备: ${device.name} - $address")

            // 检查设备是否已配对
            if (device.bondState == BluetoothDevice.BOND_BONDED) {
                result.success(true)
                return
            }

            // 创建配对请求
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                device.createBond()
                result.success(true)
            } else {
                result.error("UNSUPPORTED", "设备配对需要Android 4.4+", null)
            }
        } catch (e: Exception) {
            result.error("ERROR", "配对设备失败: ${e.message}", null)
        }
    }

    private fun connectDevice(address: String?, result: MethodChannel.Result) {
        try {
            if (address == null) {
                result.error("INVALID_ADDRESS", "设备地址无效", null)
                return
            }
            
            if (bluetoothAdapter == null) {
                result.error("UNAVAILABLE", "蓝牙不可用", null)
                return
            }
            
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                    result.error("PERMISSION_DENIED", "需要蓝牙连接权限", null)
                    return
                }
            }
            
            // 先断开现有连接
            try {
                inputStream?.close()
                outputStream?.close()
                bluetoothSocket?.close()
                inputStream = null
                outputStream = null
                bluetoothSocket = null
            } catch (e: Exception) {
                // 忽略断开连接时的错误
            }
            
            val device = bluetoothAdapter.getRemoteDevice(address)
            android.util.Log.d("BluetoothConnect", "尝试连接设备: ${device.name} - $address")
            android.util.Log.d("BluetoothConnect", "设备配对状态: ${device.bondState}")
            
            // 尝试多种UUID连接方式
            val uuids = listOf(
                UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"), // SPP
                UUID.fromString("00001124-0000-1000-8000-00805F9B34FB"), // HID
                UUID.fromString("0000110A-0000-1000-8000-00805F9B34FB")  // A2DP
            )
            
            var connected = false
            for ((index, uuid) in uuids.withIndex()) {
                try {
                    android.util.Log.d("BluetoothConnect", "尝试UUID $index: $uuid")
                    bluetoothSocket = device.createRfcommSocketToServiceRecord(uuid)
                    bluetoothSocket?.connect()
                    inputStream = bluetoothSocket?.inputStream
                    outputStream = bluetoothSocket?.outputStream
                    connected = true
                    android.util.Log.d("BluetoothConnect", "连接成功，使用UUID: $uuid")
                    break
                } catch (e: Exception) {
                    android.util.Log.d("BluetoothConnect", "UUID $index 连接失败: ${e.message}")
                    bluetoothSocket?.close()
                    bluetoothSocket = null
                    continue
                }
            }
            
            if (connected) {
                android.util.Log.d("BluetoothConnect", "连接成功")
                result.success(true)
            } else {
                android.util.Log.d("BluetoothConnect", "所有UUID连接都失败")
                result.error("CONNECTION_FAILED", "无法连接到设备，该设备可能不支持串口通信。请尝试连接蓝牙模块、Arduino等支持SPP协议的设备", null)
            }
        } catch (e: Exception) {
            result.error("ERROR", "连接设备失败: ${e.message}", null)
        }
    }

    private fun disconnect(result: MethodChannel.Result) {
        try {
            inputStream?.close()
            outputStream?.close()
            bluetoothSocket?.close()
            
            inputStream = null
            outputStream = null
            bluetoothSocket = null
            
            result.success(true)
        } catch (e: Exception) {
            result.error("ERROR", "断开连接失败: ${e.message}", null)
        }
    }

    private fun sendData(data: String?, result: MethodChannel.Result) {
        try {
            if (data == null) {
                result.error("INVALID_DATA", "数据无效", null)
                return
            }
            
            if (outputStream == null) {
                result.error("NOT_CONNECTED", "设备未连接", null)
                return
            }
            
            outputStream?.write(data.toByteArray())
            result.success(true)
        } catch (e: Exception) {
            result.error("ERROR", "发送数据失败: ${e.message}", null)
        }
    }

    private fun readData(result: MethodChannel.Result) {
        try {
            if (inputStream == null) {
                result.error("NOT_CONNECTED", "设备未连接", null)
                return
            }
            
            val buffer = ByteArray(1024)
            val bytes = inputStream?.read(buffer)
            if (bytes != null && bytes > 0) {
                val data = String(buffer, 0, bytes)
                result.success(data)
            } else {
                result.success("")
            }
        } catch (e: Exception) {
            result.error("ERROR", "读取数据失败: ${e.message}", null)
        }
    }

    private fun getConnectionState(result: MethodChannel.Result) {
        try {
            val state = if (bluetoothSocket?.isConnected == true) "connected" else "disconnected"
            result.success(state)
        } catch (e: Exception) {
            result.error("ERROR", "获取连接状态失败: ${e.message}", null)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        // 确保注销广播接收器
        if (isReceiverRegistered) {
            try {
                unregisterReceiver(bluetoothReceiver)
                isReceiverRegistered = false
            } catch (e: Exception) {
                // 忽略错误
            }
        }
    }
}
